'use strict';

const walker = require('./walker');
const escomplex = require('escomplex');
const luaparse = require('luaparse');
const fs = require('fs');
const adds = require('autodetect-decoder-stream');

const defaultConfig = {
    logicalor: true,
    switchcase: true,
    forin: true,
    newmi: true
};

/**
 * Analysis the code metrics for one module
 * @param {String} filePath The path of the module file.
 * @param {Object} tree [Optional] The abstract syntax tree of the module, 
 * generated by luaparse with `locations` enable
 * @returns {Object} The report of the module if anaysis success
 */
exports.module = (filePath, content) => {
    return escomplex.analyse(
        luaparse.parse(content, { locations: true, comments: false }),
        walker,
        defaultConfig
    );
}

/**
 * Analysis the code metrics for project files
 * @param {String} filesPath The path of the project files.
 * @returns {Object} The reports of the project if anaysis success
 */
exports.project = (filesPath) => {
    return analyseProject(filesPath);
}

function analyseProject(filesPath) {
    if (!Array.isArray(filesPath)) {
        return Promise.reject("param 'filesPath' is not an Array!");
    }

    let jobs = filesPath.map(filePath => {
        return new Promise((resolve) => {
            let stream = fs.createReadStream(filePath).pipe(new adds());
            stream.collect((error, data) => {
                resolve({
                    path: filePath,
                    ast: luaparse.parse(data, { locations: true, comments: false })
                });
            });
        });
    });
    return Promise.all(jobs)
        .then(modules => {
            return escomplex.analyse(modules, walker, defaultConfig);
        });
}
